<template>
  <eui-page-frame topHeight="250" bottomHeight="80">
    <template #top>
      <view class="navigation menu-seach">
        <eui-nav-bar :title="title" color="#000000" rightIcon=""></eui-nav-bar>
        <eui-search-bar @confirm="screenOperation" @clear="screenOperation(false)" v-model="seachText"
                        :placeholder="placeholder" radius="100"></eui-search-bar>
      </view>
    </template>
    <scroll-view scroll-y style="height: 100%;" @scrolltolower="lower">
      <view class="list-card">
        <view class="uni-list" v-if="isRadio">
          <radio-group @change="radioChange">
            <label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in selectDataArray"
                   :key="index">
              <view>
                <radio :value="index" activeBackgroundColor="#02B7E6" :borderColor="themeColor" :class="[theme]" style="transform:scale(0.8)" />
              </view>
              <view>
                <view>{{item.preText||''}}[{{ item.value }}]{{ item.text }}</view>
              </view>
            </label>
          </radio-group>
        </view>
        <view class="uni-list" v-else>
          <checkbox-group @change="checkboxChange">
            <label class="uni-list-cell uni-list-cell-pd" v-for="(item) in selectDataArray"
                   :key="item.value">
              <view>
                <checkbox :value="item.value" :checked="checkbox.includes(item.value)"
                          activeBackgroundColor="#02B7E6" iconColor="#FFFFFF" :class="[theme]" style="transform:scale(0.8)" />
              </view>
              <view>
                <view>[{{ item.value }}]{{ item.text }}</view>
              </view>
            </label>
          </checkbox-group>
        </view>
      </view>
    </scroll-view>>
    <template #bottom>
      <view class="bt-button">
        <eui-button type="max2" title="取消" @click="cancel" />
        <eui-button type="max" title="确定" @click="ConfirmReturn" />
      </view>
    </template>
  </eui-page-frame>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from "@dcloudio/uni-app";
import useService from '@/hooks/useService';
import {useLoginStore} from "@/store/modules/useLoginStore";
import {useMainStore} from "@/store/modules/store";
import { storeToRefs } from 'pinia';
import { useThemeStore } from '@/store/themeStore';
const themeStore = useThemeStore(); // 主题
const { theme } = storeToRefs(themeStore);
const themeColor = ref(themeStore.theme == 'theme-blue' ? '#02B7E6' : '#FF6430')

const mainService = useService({ prefix: "mainApi" });
const bcService = useService({ prefix: "bcApi" });
const LoginStore = useLoginStore();
const mainStore = useMainStore();

const CurrentPage = ref(1);
const PageSize = ref(20);
const RowsCount = ref(0);
const PageCount = ref(1);
const title = ref('');
const type = ref('');
const storeId = ref('');
const partnerNo = ref('');
const isRadio = ref(true);
const seachText = ref('');
const IsMult = ref('')
const selectDataArray = ref([]);
const current = ref(-1)
const checkbox = ref([]); //选中
const c_height = ref(0);

const placeholder = ref('请输入编码或名称')

const selectCfgs = [
  { text: '选择人员', value: 'user', codeCol: 'c_userno', nameCol: 'c_name' },
  { text: '选择部门', value: 'depart', codeCol: 'c_adno', nameCol: 'c_name' },
  { text: '选择品牌', value: 'brand', codeCol: 'c_bcode', nameCol: 'c_name' },
  { text: '选择商户', value: 'partner', codeCol: 'c_no', nameCol: 'c_name' },
  { text: '选择品类', value: 'gdsClass', codeCol: 'c_ccode', nameCol: 'c_name' },
  { text: '选择铺位', value: 'counter', codeCol: 'c_no', nameCol: 'c_name' },
  { text: '选择费用项目', value: 'feeItem', codeCol: 'c_fee_code', nameCol: 'c_fee_name' },
  { text: '选择合同', value: 'contract', codeCol: 'c_con_no', nameCol: 'c_version',preTextCol:'c_provider_name' },
  { text: '选择仓库', value: 'wno', codeCol: 'c_wno', nameCol: 'c_name' },
  { text: '选择采购地', value: 'plno', codeCol: 'c_no', nameCol: 'c_name' },
]

const curSelectCfg = ref(selectCfgs[0]);

onLoad(async (option) => {
  if (option) {
    const { loginInfo } = mainStore;
    console.log(option);
    type.value = option.type;
    isRadio.value = option.IsMult && option.IsMult == '是' ? false : true;
    title.value = selectCfgs.find(item => item.value == option.type)?.text || '选择数据弹出框';
    curSelectCfg.value = selectCfgs.find(item => item.value == option.type) || selectCfgs[0];
    if (type.value == 'contract') {
      placeholder.value = '请输入合同号或版本号';
    }
    console.log('curSelectCfg', curSelectCfg.value);
    storeId.value = option.storeId || loginInfo.sUserStore;
    console.log('storeId', storeId.value);
    partnerNo.value = option.partnerNo || '';
    console.log('partnerNo', partnerNo.value);
    await querydata(false);
    if (option.IsMult == '是' && option.SelectedItems) {
      checkbox.value = option.SelectedItems.split(",");;
    }
  }
})
const radioChange = (evt) => {
  console.log('radioChange', evt)
  current.value = evt.detail.value;
}
const checkboxChange = (evt) => {
  checkbox.value = evt.detail.value;
}
const lower = async () => {
  // CurrentPage: 1, //第几页  PageSize: 10, //每页10条  RowsCount: 0, //总条数 PageCount: 1, //总页数
  if (CurrentPage.value < PageCount.value) {
    CurrentPage.value = CurrentPage.value + 1;
    // console.log(this.PageCount, this.CurrentPage, this.PageSize, this.PageCount);
    await querydata(true);
  }
}
const querydata = async (e?: boolean) => {
  if (!e) {
    CurrentPage.value = 1;
  }
  const req = {
    IsNotPage: false,
    CurrentPage: CurrentPage.value,
    PageSize: PageSize.value,
    WhereList: [
    ]
  };
  if (seachText.value) {
    req.WhereList.push({
      c_col: curSelectCfg.value.nameCol,
      c_oper: "相似",
      c_value: seachText.value,
      c_logic: "或者",
    });
    req.WhereList.push({
      c_col: curSelectCfg.value.codeCol,
      c_oper: "相似",
      c_value: seachText.value,
      c_logic: "而且",
    });
  }

  let res;
  switch (type.value) {
    case 'user':
      res = await mainService.request('h5user', 'EnjoyQueryList', req);
      break;
    case 'depart':
      res = await mainService.request('h5depart', 'EnjoyQueryList', req);
      break;
    case 'brand':
      res = await bcService.request('品牌定义', 'EnjoyQueryList', req);
      break;
    case 'partner':
      res = await bcService.request('弹窗通用查询', 'FetchPartnerList', req);
      break;
    case 'gdsClass':
      res = await bcService.request('商品品类定义', 'EnjoyQueryList', req);
      break;
    case 'counter':
      if(storeId.value){
        req.WhereList.push({
          c_col: 'c_store_id',
          c_oper: "等于",
          c_value: storeId.value,
          c_logic: "而且",
        });
      }
      req.WhereList.push({
        c_col: "c_status",
        c_logic: "而且",
        c_oper: "等于",
        c_value: "1"
      });
      res = await bcService.request('铺位定义', 'EnjoyQueryList', req);
      break;
    case 'feeItem':
      res = await bcService.request('费用项目定义', 'EnjoyQueryList', req);
      break;
    case 'contract':
      req.WhereList.push({
        c_col: "c_status",
        c_logic: "而且",
        c_oper: "包含",
        c_value: "2,3"
      })
      if(partnerNo.value){
        req.WhereList.push({
          c_col: 'c_provider',
          c_oper: "等于",
          c_value: partnerNo.value,
          c_logic: "而且",
        });
      }
      res = await bcService.request('合同查询', 'EnjoyQueryList', req);
      break;
    case 'wno':
      if (storeId.value) {
        req.WhereList.push({
          c_col: 'c_store_id',
          c_oper: "等于",
          c_value: storeId.value,
          c_logic: "而且",
        });
      }
      res = await bcService.request('弹窗通用查询', 'FetchWno', req);
      break;
    case 'plno':
      res = await bcService.request('生鲜采购地维护', 'EnjoyQueryList', req);
      break;
  }

  if (res) {
    const ObjectData = res?.ReturnObject?.map(item => {
      return {
        ...item,
        text: item[curSelectCfg.value.nameCol],
        value: item[curSelectCfg.value.codeCol],
        preText:curSelectCfg.value.preTextCol?item[curSelectCfg.value.preTextCol]:"",
      }
    })
    PageCount.value = res.PageCount;
    if (ObjectData.length > 0) {
      selectDataArray.value = selectDataArray.value.concat(ObjectData);
    }
  }
}
// 确定返回
const ConfirmReturn = () => {
  if (isRadio.value) {
    if (current.value === -1) {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: '请先勾选！'
      });
      return false;
    }
    console.log('current.value', current.value)
    AddSelectDataToPrePage(selectDataArray.value[current.value])
  } else {
    if (checkbox.value.length === 0) {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: '请先勾选！'
      });
      return false;
    }
    let DataArray = {
      list: checkbox.value,
    }
    AddSelectDataToPrePage(DataArray)
  }
}
// 取消
const cancel = () => {
  uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
    delta: 1
  });
}
// 带上选择的数据返回上级
const AddSelectDataToPrePage = (param) => {
  //通知上一界面刷新
  if (param) {
    try {
      let pages = getCurrentPages(); //获取所有页面栈实例列表
      let prevPage = pages[pages.length - 2]; //上一页页面实例
      prevPage.$vm.$.exposed.SelectionChanged(type.value, param); //执行函数也是同理
      uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
        delta: 1
      });
    } catch (e) {
      console.log(e);
      //TODO handle the exception
    }
  }
}
const screenOperation = async (e) => {
  selectDataArray.value = [];
  if (!e) {
    seachText.value = '';
  }
  else {
    seachText.value = e.value;
  }
  await querydata(false);
}
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex: 1;
  flex-direction: column;
  background-color: #F2F2F2;
  padding: 0px !important
}

.content-img {
  background-color: #FFFFFF;
  background-size: 100% 420rpx;
  background-repeat: no-repeat;
  width: 100%;
}

.navigation {
  background-color: #FFFFFF;
  flex: 0 0 auto;
  margin-bottom: 0;
}

.list-card {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border-radius: 20rpx;
  background-color: #ffffff;
}

.list-card-content {
  width: 100%;
  height: 100%;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  padding: 0rpx 28rpx;
}

.uni-list {
  background-color: #fff;
  position: relative;
  width: 100%;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  flex-direction: column;
}

uni-radio-group,
uni-checkbox-group {
  width: 100%;
}

uni-radio-group {
  display: block;
}

.uni-list-cell {
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-box-pack: justify;
  -webkit-justify-content: space-between;
  justify-content: space-between;
  -webkit-box-align: center;
  -webkit-align-items: center;
  align-items: center;
  -webkit-box-pack: start;
  -webkit-justify-content: flex-start;
  justify-content: flex-start;
}

.uni-list-cell-pd {
  padding: 10px;
}

.uni-list-cell::after {
  position: absolute;
  z-index: 3;
  right: 0;
  bottom: 0;
  left: 0px;
  height: 1px;
  content: "";
  -webkit-transform: scaleY(.5);
  transform: scaleY(.5);
  background-color: #c8c7cc;
}

.uni-list-cell:last-child::after {
  height: 0px;
}

.uni-list:after {
  position: absolute;
  z-index: 10;
  right: 0;
  bottom: 0;
  left: 0;
  height: 1px;
  content: "";
  -webkit-transform: scaleY(.5);
  transform: scaleY(.5);
  background-color: #c8c7cc;
}

.bt-button {
  // height: 80rpx;
  background: #FFFFFF;
  padding: 10rpx 0rpx;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

::v-deep .uni-checkbox-input {
  border-radius: 50%;
  // background: var(--theme-bgc-color);
  border: 1px solid var(--theme-color);
}

::v-deep .uni-checkbox-input svg {
  transform: translate(-100%, -100%) scale(1);
  background: var(--theme-bgc-color);
  border-radius: 50%;
  color: #fff !important;
  top: 22px;
  left: 22px;
}

::v-deep .uni-checkbox-input svg path {
  fill: #fff !important;
  transform: translate(10%, 10%) scale(0.8);
}
</style>
